package com.fanbai.score.common.Utils;


import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.PhoneNumberUtils;
import android.widget.Toast;


import com.fanbai.score.R;
import com.fanbai.score.common.Utils.log.YD_Log;
import com.fanbai.score.common.dialog.MyAlertDialog;
import com.fanbai.score.common.dialog.OnMyAlertDialogClick;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 常用的通用小功能
 *
 * @author NB
 */
public class CommonUtil {

    /**
     * 使用浏览器打开一个网址
     *
     * @param url
     */
    public static void openBrowser(Context ctx, String url) {
        Intent webIntent = new Intent(Intent.ACTION_VIEW);
        webIntent.setData(Uri.parse(url.trim()));
        YD_Log.writeLog("http", "打开url:" + url);
        try {
            ctx.startActivity(webIntent);
        } catch (ActivityNotFoundException ex0) {
            // 部分系统不能打开https协议,只能指定浏览器打开
            try {
                YD_Log.writeLog("http", "url无法启动浏览器，指定打开系统自带浏览器");
                webIntent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
                ctx.startActivity(webIntent);
            } catch (ActivityNotFoundException ex) {
                YD_Log.writeLog("http", "浏览器Activity未找到【" + url + "】 错误信息：" + ex.getMessage());
                Toast.makeText(ctx, "未找到可用的浏览器", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 由Uri获取文件绝对路径(不同的SDK版本获取方式，有所不同)<br/>
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getPathFromUri(Context context, Uri uri) {
        String filename = "";
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        if (isKitKat) {
            filename = UriUtils.getPathFromUri_19_high(context, uri);
        } else {
            filename = UriUtils.getPathFromUri_19_low(context, uri);
        }
        return filename;
    }

    /**
     * 获得当前的版本信息
     *
     * @return
     */
    public static String getVersion(Context ctx) {
        try {
            PackageManager manager = ctx.getPackageManager();
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return AppUtils.getResource().getString(R.string.versionName);
        }
    }

    /**
     * 获取当前时间（yyyy-MM-dd HH:mm）
     * @return
     */
    public static String getTimeData(){
        long time =System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        Date d1 = new Date(time);
        return format.format(d1);
    }
    public static String getDateString(String pattern) {
        long time =System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();  
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date d1 = new Date(time);
        return format.format(d1);
    }
    /**
     * 获取起始时间到结束时间的天数
     * @param start
     * @param end
     * @return
     */
    public static int timeCompare(String start, String end){
        //格式化时间
        SimpleDateFormat CurrentTime= new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date beginTime=CurrentTime.parse(start);
            Date endTime=CurrentTime.parse(end);
            //判断是否大于两天
            return (int)((endTime.getTime() - beginTime.getTime())/(24*60*60*1000));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            return 0;
        }

    }

    /**
     * 拨号方法
     */
    public static void callPhone(Activity activity, String number) {
        if(number == null || number.equals("")){
            return;
        }
        if(!checkCallPermission(activity)){
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:"+number));
        activity.startActivity(intent);
    }
    /**
     * 直接调用短信接口发短信
     * @param phoneNumber
     */
    public static void sendSMS(Activity activity, String phoneNumber){
        if(PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)){
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
            intent.putExtra("sms_body", "");
            activity.startActivity(intent);
        }
    }

    /**
     * 检查蓝牙操作所需权限是否全部开启
     * @return
     */
    public static boolean checkBlePermission(final Activity ctx){
        PermissionUtils perm = PermissionUtils.getInstance();
        String[] perms = perm.filtRequestPerm(ctx, perm.GROUP_STORAGE, perm.GROUP_BLUETOOTH,
                perm.GROUP_LOCATION);//perm.GROUP_CAMERA 可选
        if (perms == null || perms.length == 0) {
            return true;
        }
        new MyAlertDialog().showDialog(ctx, "提示",
                "所需权限不足，请开启手机定位和蓝牙相关的权限，去开启？", new OnMyAlertDialogClick() {
            @Override
            public void onMyAlertDialogClick(boolean is, String... str) {
                if(is){
                    ctx.startActivity(getAppDetailSettingIntent());
                }
            }
        });
        return false;
    }

    public static boolean checkCallPermission(final Activity ctx){
        PermissionUtils perm = PermissionUtils.getInstance();
        String[] perms = perm.filtRequestPerm(ctx, perm.GROUP_CALL);
        if (perms == null || perms.length == 0) {
            return true;
        }
        new MyAlertDialog().showDialog(ctx, "提示",
                "所需权限不足，请开启拨打电话相关的权限，去开启？", new OnMyAlertDialogClick() {
                    @Override
                    public void onMyAlertDialogClick(boolean is, String... str) {
                        if(is){
                            ctx.startActivity(getAppDetailSettingIntent());
                        }
                    }
                });
        return false;
    }

    public static boolean checkCameraPermission(final Activity ctx){
        PermissionUtils perm = PermissionUtils.getInstance();
        String[] perms = perm.filtRequestPerm(ctx, perm.GROUP_STORAGE, perm.GROUP_CAMERA);
        if (perms == null || perms.length == 0) {
            return true;
        }
        new MyAlertDialog().showDialog(ctx, "提示",
                "所需权限不足，请开启拨拍照以及图库相关的权限，去开启？", new OnMyAlertDialogClick() {
                    @Override
                    public void onMyAlertDialogClick(boolean is, String... str) {
                        if(is){
                            ctx.startActivity(getAppDetailSettingIntent());
                        }
                    }
                });
        return false;
    }

    public static boolean checkPermission(final Activity ctx){
        PermissionUtils perm = PermissionUtils.getInstance();
        String[] perms = perm.filtRequestPerm(ctx, perm.GROUP_STORAGE, perm.GROUP_CAMERA);
        if (perms == null || perms.length == 0) {
            return true;
        }
        new MyAlertDialog().showDialog(ctx, "提示",
                "所需权限不足，请开启相关权限，去开启？", new OnMyAlertDialogClick() {
                    @Override
                    public void onMyAlertDialogClick(boolean is, String... str) {
                        if(is){
                            ctx.startActivity(getAppDetailSettingIntent());
                        }
                    }
                });
        return false;
    }

    /** 
      * 获取应用详情页面intent 
      * 
      * @return 
      */
    private static Intent getAppDetailSettingIntent(){
         Intent localIntent = new Intent();
         localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         if (Build.VERSION.SDK_INT >= 9) {
             localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
             localIntent.setData(Uri.fromParts("package", "com.fanbai.score", null));
             } else if (Build.VERSION.SDK_INT <= 8) {
             localIntent.setAction(Intent.ACTION_VIEW);
             localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", "com.ydiot.ssp");
             }
         return localIntent;
    }

}
